package com.itheima.tlias08_14.controller;

import com.alibaba.fastjson.JSONObject;
import com.itheima.tlias08_14.utils.ResultUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("cookie")
public class TestCookieController {

    /**
     * 保存cookie
     * @param response
     * @return
     */
    @GetMapping("save")
    public ResultUtil saveCookie(HttpServletResponse response) {
        Cookie cookie = new Cookie("username", "summer");
        response.addCookie(cookie);
        Cookie cookie1 = new Cookie("password", "2278827863");
        response.addCookie(cookie1);
        return ResultUtil.success();
    }

    /**
     * 获取cookie
     * @param response
     * @return
     */
    @GetMapping("get")
    public ResultUtil getCookie(HttpServletRequest response) {
        Cookie[] cookies = response.getCookies();
        JSONObject jsonObject = new JSONObject();
        for (Cookie cookie : cookies) {
            jsonObject.put(cookie.getName(), cookie.getValue());
        }
        return ResultUtil.success(jsonObject);
    }


    /**
     * 保存session
     * @param session
     * @return
     */
    @GetMapping("saveSession")
    public ResultUtil saveSession(HttpSession session) {
        session.setAttribute("username", "summer");
        session.setAttribute("password", "damouren");
        return ResultUtil.success();
    }

    /**
     * 获取session
     * @param session
     * @return
     */
    @GetMapping("getSession")
    public ResultUtil getSession(HttpSession session) {
        return ResultUtil.success(session.getAttribute("username") + ":" + session.getAttribute("password"));
    }


}
